import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function GET(
  req: NextRequest,
  { params }: { params: { id: string; submissionId: string } }
) {
  const session = await getServerSession(authOptions)

  // Allow teacher, admin, or the student who owns the submission to view it.
  if (!session?.user) {
    return NextResponse.json({ error: 'Forbidden. Please log in.' }, { status: 403 });
  }

  const { id: experimentId, submissionId } = params;

  if (!experimentId || !submissionId) {
    return NextResponse.json({ error: 'Experiment ID and Submission ID are required' }, { status: 400 });
  }

  try {
    const formalSubmission = await prisma.submission.findUnique({
      where: { id: submissionId },
      include: {
        user: { // Changed from student to user
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
        experiment: {
          select: {
            id: true,
            title: true,
          },
        },
        stageSubmissions: {
          include: {
            stage: {
              select: {
                id: true,
                title: true,
                description: true,
                order: true,
                type: true,
                content: true, 
              },
            },
          },
          orderBy: {
            stage: {
                order: 'asc'
            }
          }
        },
      },
    });

    if (!formalSubmission) {
      return NextResponse.json({ error: 'Submission snapshot not found' }, { status: 404 });
    }

    if (formalSubmission.experimentId !== experimentId) {
        return NextResponse.json({ error: 'Submission snapshot does not belong to this experiment' }, { status: 400 });
    }

    // Authorization check: Only teachers, admins, or the student owner can view.
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN' && formalSubmission.userId !== session.user.id) {
      return NextResponse.json({ error: 'Forbidden. You do not have permission to view this submission.' }, { status: 403 });
    }

    return NextResponse.json({ submission: formalSubmission });

  } catch (error) {
    console.error(`Error fetching submission snapshot ${submissionId} for experiment ${experimentId}:`, error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
} 